'use strict';
// 云函数代码，传入context
const uniID = require('uni-id-common')
exports.main = async (event, context) => {
	//event为客户端上传的参数
	// console.log('event : ', event)
	// 云函数代码，传入context
	// const uniID = require('uni-id-common');

	const uniIDIns = await uniID.createInstance({ // 创建uni-id实例
		context: context,
		// config: {} // 完整uni-id配置信息，使用config.json进行配置时无需传此参数
	})
	let info = await uniIDIns.checkToken(event.uniIdToken);
	let uid = info.uid;
	const db = uniCloud.database();
	const dbCmd = db.command
	// console.log(event,context,'22222222222')
	let counts = await db.collection('pj_love').where({
		user_id: uid,
		pj_id:event.id
	}).count()
	
	if (counts.total) {
		
		await db.collection('pj').doc(event.id).update({
			love: dbCmd.inc(-1)
		})
		let r = await db.collection('pj_love').where({
			user_id: uid,
			pj_id:event.id
		}).remove()
		if (r) {
			let pj = await db.collection('pj').doc(event.id).field({
				'love': true
			}).get()
			
			return pj.data[0]['love'];
		} else {
			return {
				errCode: 'error',
				errMsg: 'error'
			}
		}
	} else {
		console.log(event.id,'22222')
		await db.collection('pj').doc(event.id).update({
			love: dbCmd.inc(1)
		})
		let r = await db.collection('pj_love').add({
			user_id: uid,
			pj_id:event.id
		});

		if (r) {
			let pj = await db.collection('pj').doc(event.id).field({
				'love': true
			}).get()
			return pj.data[0]['love'];
		} else {
			return {
				errCode: 'error',
				errMsg: 'error'
			}
		}
	}



};